let username = document.querySelector(".edit_box input");  // 把名字设置一下
let values = localStorage.getItem("jwt");
let old_name;  // 存储旧名字用的
fetch('/user_message/userBrief', {
    method: 'GET',
    headers: {
        'authorization': values
    }
}).then(response => {
    if (!response.ok) {
        throw new Error('网络请求错误: ' + response.status + ' ' + response.statusText);
    }
    return response.json();
}).then(data => {
    username.value = data[0]['username']; // 用户名
    old_name = username.value;
}).catch(error => {
    console.log(error);
})

let submit = document.querySelector(".send input")

submit.addEventListener('click', (e) => {
    e.preventDefault(); // 阻止表单默认提交行为
    // 验证用户名是否改变且不为空，长度也要小于15个字符
    if (username.value === old_name) {
        window.location.href = "/webpage_copy/my/my-editdata.html";
    } else if (username.value.trim() === '') {
        alert('用户名不能为空！');
    } else if (username.value.length >= 16) {
        alert('用户名长度必须小于16个字符！');
    } else {
        // 如果验证通过，执行更新操作
        let data = {
            username: username.value
        };
        fetch('/user_message/updateUsername', {
            method: 'POST',
            headers: {
                'authorization': values,
                'content-Type': 'application/json'
            },
            body: JSON.stringify(data)
        }).then(response => {
            if (!response.ok) {
                throw new Error('网络请求错误: ' + response.status + ' ' + response.statusText);
            }
            return response.json();
        }).then(() => {
            // 更新成功后的操作
            window.location.href = "/webpage_copy/my/my-editdata.html";
        })
        .catch(error => {
            console.error(error);
        });
    }
});